package com.cloud.bssp.nio.bytebuffer;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @description： 测试buffer的读写
 * @author：weirx
 * @date：2021/11/2 13:54
 * @version：3.0
 */
public class test {
    public static void main(String[] args) {

        try (RandomAccessFile file = new RandomAccessFile("C:\\Users\\P50\\Desktop\\text.txt", "rw")) {
            FileChannel channel = file.getChannel();
            //申请大小为10的buffer
            ByteBuffer buffer = ByteBuffer.allocate(10);
            System.out.println("当前position大小：" + buffer.position());
            do {
                // 向 buffer 写入
                int len = channel.read(buffer);
                System.out.println("当前position大小：" + buffer.position());
                System.out.println("读到字节数：" + len +",position = " + buffer.position());
                if (len == -1) {
                    break;
                }
                // 切换 buffer 读模式
                buffer.flip();
                System.out.println("当前position大小：" + buffer.position());
                while (buffer.hasRemaining()) {
                    System.out.println((char) buffer.get() +",position = " + buffer.position());
                    System.out.println("当前position大小：" + buffer.position());
                }
                // 切换 buffer 写模式
                buffer.clear();
            } while (true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
